import os
import yaml

def get_project_root():
    """获取项目根目录"""
    return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def get_data_path():
    """获取data目录路径"""
    return os.path.join(get_project_root(), "data")

# 往yaml文件中写入数据
def write_yaml(filename, data):
    data_dir = get_data_path()
    # 确保data目录存在
    os.makedirs(data_dir, exist_ok=True)

    file_path = os.path.join(data_dir, filename)
    with open(file_path, mode="a+", encoding="utf-8") as f:
        yaml.safe_dump(data, stream=f)

# 读取yaml文件中的数据
def read_yaml(filename, key):
    data_dir = get_data_path()
    file_path = os.path.join(data_dir, filename)

    with open(file_path, mode="r", encoding="utf-8") as f:
        data = yaml.safe_load(f)
        return data[key]

# 清空yaml文件
def clear_yaml(filename):
    data_dir = get_data_path()
    file_path = os.path.join(data_dir, filename)

    with open(file_path, mode="w", encoding="utf-8") as f:
        f.truncate()